//
//  YZECommunityViewController.m
//  yilutongxing
//
//  Created by 赵继申 on 17/3/11.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "YZECommunityViewController.h"
#import "YZECommunityTableViewCell2.h"
#import "YZECommunityTableViewCell4.h"
#import "PYSearch.h"
#import "TopicTableView.h"
#import "KnowledgeTableView.h"
#import "YZEFaBiaoViewController.h"
#import "Type_topicTableViewController.h"
#import "TopCollectionViewCell.h"
#import "KnowledgeDetailViewController.h"
#import "TopicDetailViewController.h"

#define URL_GetTopics @"/api/topics"
#define URL_GetKnowledages @"/api/transplant-knowledges"
#define URL_SearchTopicsAndKnowledages @"/api/_search/topicAndKnowledge?query="

@interface YZECommunityViewController ()<PYSearchViewControllerDelegate,PYSearchViewControllerDataSource,UIScrollViewDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UIButton *topBtn;
@property (weak, nonatomic) IBOutlet UIButton *knowledgeBtn;
@property (weak, nonatomic) IBOutlet UIView *viewOne;
@property (weak, nonatomic) IBOutlet UIView *viewTwo;

@property(nonatomic,strong)UIScrollView *scrollView;

@property(nonatomic,strong)TopicTableView *topTableView;
@property(nonatomic,strong)KnowledgeTableView *knowledgeTableView;

@property(nonatomic,strong)NSMutableArray *topicArr;
@property(nonatomic,strong)NSMutableArray *knowledgeArr;
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;

@property (nonatomic,copy) NSString *cellTitle;
@property (nonatomic,assign )BOOL type;

@property (nonatomic ,assign)BOOL tag;
@property (nonatomic)UIViewController *vc;
@end

@implementation YZECommunityViewController

- (IBAction)searchViewTap:(id)sender {
    [self tapSearchView];
}
- (IBAction)clickBtn:(UIButton *)sender {
    if (sender.tag==0) {
        [UIView animateWithDuration:.5 animations:^{
            self.scrollView.contentOffset=CGPointMake(0, 0);

        }];
        self.viewOne.hidden=NO;
        [self.topBtn setTintColor:Bluecolor];
        self.viewTwo.hidden=YES;
        [self.knowledgeBtn setTintColor:[UIColor blackColor]];
        
        self.type = YES;
    }
    else if (sender.tag==1){
        [UIView animateWithDuration:.5 animations:^{
            self.scrollView.contentOffset=CGPointMake(SCREEN_WIDTH, 0);

        }];
        self.viewOne.hidden=YES;
        [self.topBtn setTintColor:[UIColor blackColor]];
        self.viewTwo.hidden=NO;
        [self.knowledgeBtn setTintColor:Bluecolor];
        self.type = NO;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.type = YES;
    self.m_labelTitle.text = @"社区";
    self.searchView.layer.masksToBounds=YES;
    self.searchView.layer.cornerRadius=16;
    [self creat_fabu_btn];  //调用发布按钮方法
   
    [self initUI];
    
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:URL_GetTopics] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
       self.topTableView.topicArr= [BaseModel mj_objectArrayWithKeyValuesArrayAdd:responseObject];
        [self.topTableView reloadData];
    }];
    
    
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:URL_GetKnowledages] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        self.knowledgeTableView.knowledgeArr= [BaseModel mj_objectArrayWithKeyValuesArrayAdd:responseObject];
        [self.knowledgeTableView reloadData];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fabu) name:@"fabu_btn_click" object:nil];
    
    [self creatCollectionView];
}

- (void)viewWillAppear:(BOOL)animated{
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:URL_GetTopics] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        self.topTableView.topicArr= [BaseModel mj_objectArrayWithKeyValuesArrayAdd:responseObject];
        [self.topTableView reloadData];
    }];
    
    
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:URL_GetKnowledages] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        self.knowledgeTableView.knowledgeArr= [BaseModel mj_objectArrayWithKeyValuesArrayAdd:responseObject];
        [self.knowledgeTableView reloadData];
    }];
}

-(void)creatCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //滑动方向(默认是垂直滚动)
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.myCollectionView.collectionViewLayout = layout;
    self.myCollectionView.showsHorizontalScrollIndicator = NO;
    self.myCollectionView.showsVerticalScrollIndicator = NO;
    self.myCollectionView.delegate=self;
    self.myCollectionView.dataSource=self;
    //注册cell单元格
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"TopCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 7;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TopCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    self.cellTitle = cell.typeLable.text;
    [cell showCollectViewItem:indexPath.item];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    Type_topicTableViewController *tvc = [Type_topicTableViewController new];
    tvc.typeID = indexPath.item;
    tvc.type = self.type;
    self.title = @"";
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController:tvc animated:YES];
     NSLog(@"点击%ld",(long)indexPath.item);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(50, 90);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(15, 20, 15, 20);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 40;
}
-(void)fabu{
    YZEFaBiaoViewController *fabu=[YZEFaBiaoViewController new];
    UINavigationController *navi=[[UINavigationController alloc]initWithRootViewController:fabu];
    [self presentViewController:navi animated:YES completion:nil];

}
-(void)initUI{
    self.navigationItem.hidesBackButton=NO;

    self.scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 164+90, SCREEN_WIDTH, SCREEN_HEIGHT-164-44)];
    self.scrollView.contentSize=CGSizeMake(SCREEN_WIDTH*2,0);
    self.scrollView.delegate=self;
    [self.view addSubview:self.scrollView];
    self.scrollView.bounces=NO;
    self.scrollView.pagingEnabled=YES;
    self.scrollView.showsHorizontalScrollIndicator=NO;
    self.scrollView.scrollEnabled  =NO;
    
    self.topTableView=[[TopicTableView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, self.scrollView.frame.size.height-100)];
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeToLetfAction)];
    swipe.direction = UISwipeGestureRecognizerDirectionLeft;
    
    [self.topTableView addGestureRecognizer:swipe];
    [self.scrollView addSubview:self.topTableView];
    
     self.knowledgeTableView=[[KnowledgeTableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH,0, SCREEN_WIDTH,self.scrollView.frame.size.height-100)];
    
    UISwipeGestureRecognizer *swipe1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeToRightAction)];
    swipe1.direction = UISwipeGestureRecognizerDirectionRight;
    [self.knowledgeTableView addGestureRecognizer:swipe1];
    
     [self.scrollView addSubview:self.knowledgeTableView];
}
#pragma ScrollView Deleagte
-(void)swipeToLetfAction{
    NSLog(@"向右滑动");
    CGPoint temp = self.scrollView.contentOffset;
    temp.x = SCREEN_WIDTH;
    [UIView animateWithDuration:.5 animations:^{
        self.scrollView.contentOffset = temp;
        self.viewOne.hidden=YES;
        [self.topBtn setTintColor:[UIColor blackColor]];
        self.viewTwo.hidden=NO;
        [self.knowledgeBtn setTintColor:Bluecolor];
    } completion:^(BOOL finished) {
        self.type = NO;
        
    }];
}
-(void)swipeToRightAction{
    NSLog(@"向左滑动");
    CGPoint temp = self.scrollView.contentOffset;
    temp.x = 0;
    [UIView animateWithDuration:.5 animations:^{
        self.scrollView.contentOffset = temp;
        self.viewOne.hidden=NO;
        [self.topBtn setTintColor:Bluecolor];
        self.viewTwo.hidden=YES;
        [self.knowledgeBtn setTintColor:[UIColor blackColor]];
    } completion:^(BOOL finished) {
        self.type = YES;
    }];
    ;
}
-(void)tapSearchView{
    self.tag = false;
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 44) style:UITableViewStyleGrouped];
    //创建控制器
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:nil searchBarPlaceholder:NSLocalizedString(@"搜索",@"搜索类型") didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        
        [UIView animateWithDuration:.1 animations:^{
            tableView.frame = CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT-44);
        } completion:nil];
        self.tag = true;
        
        // 开始搜索执行以下代码
        NSString *str=[BASE stringByAppendingString:URL_SearchTopicsAndKnowledages];
        
        NSString *path=[str stringByAppendingString:searchText];
        
        //如果网址中出现了 中文 需要进行URL编码
        path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        [[YZENetwork sharedInstace]getRequestWithUrl:path parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
            self.topicArr = [BaseModel mj_objectArrayWithKeyValuesArrayAdd:responseObject[@"topics"]];
            for (BaseModel *model in self.topicArr) {
                model.createdUser = model.user;
            }
            self.knowledgeArr = [BaseModel mj_keyValuesArrayWithObjectArrayAdd:responseObject[@"knowledges"]];
            
            [tableView reloadData];
        }];
    }];
    // 4. 设置代理
    searchViewController.delegate = self;
    searchViewController.showSearchHistory = NO;
    //     searchViewController.searchHistoryStyle =PYSearchHistoryStyleCell; // 搜索历史风格根据选择
    searchViewController.cancelButton.tintColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1];
    searchViewController.cancelButton.title = @"取消";
    self.vc = searchViewController;
    tableView.delegate = self;
    tableView.dataSource = self;
    [searchViewController.view addSubview:tableView];
    [tableView registerNib:[UINib nibWithNibName:@"YZECommunityTableViewCell2" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"YZECommunityTableViewCell2"];
    [tableView registerNib:[UINib nibWithNibName:@"YZECommunityTableViewCell4" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"YZECommunityTableViewCell4"];
    
    // 5. 跳转到搜索控制器
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    
    [self presentViewController:nav animated:YES completion:nil];

}
#pragma mark - PYSearchViewControllerDelegate
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText{
    if (self.tag&&searchText.length) {
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return self.topicArr.count;
        default:
            return self.knowledgeArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YZECommunityTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"YZECommunityTableViewCell2" forIndexPath:indexPath];
        BaseModel *model = self.topicArr[indexPath.row];
        [cell showData:model superWidth:tableView.width];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        YZECommunityTableViewCell4 *cell = [tableView dequeueReusableCellWithIdentifier:@"YZECommunityTableViewCell4" forIndexPath:indexPath];
        NSDictionary *model=self.knowledgeArr[indexPath.row];
        [cell showData:model];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.separatorInset = UIEdgeInsetsMake(0, tableView.frame.size.width, 0, 0);
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        if (indexPath.section==0) {
            BaseModel *model = self.topicArr[indexPath.row];
            YZECommunityTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"YZECommunityTableViewCell2"];
            CGFloat h = [cell cellHeight:model superWidth:tableView.width];
            return h;
        }else{
            return 90;
        }
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"全部话题";
    }else{
        return @"全部移植知识";
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        TopicDetailViewController *detail=[TopicDetailViewController new];
        UINavigationController *navi=[[UINavigationController alloc]initWithRootViewController:detail];
        BaseModel *model =self.topicArr[indexPath.row];
        detail.topicDetail=model;
        [self.vc presentViewController:navi animated:YES completion:nil];
        
    }else{
        KnowledgeDetailViewController *detail=[KnowledgeDetailViewController new];
        UINavigationController *navi=[[UINavigationController alloc]initWithRootViewController:detail];
        NSDictionary *model=self.knowledgeArr[indexPath.row];
        [detail getWebID:model[@"id"]];
        [self.vc presentViewController:navi animated:YES completion:nil];
        
    }
}
@end
